$(function(){

	// alert($("#fld_city").length);
	
	var profile_form = $("#profile_form");
	prepare_before_show();

	profile_form.bind("submit", function(){
		return prepare_before_send();
		// return false;	
	});

	$("#fld_city").autocomplete({
		minLength: 2,
		delay: 500,
		
		//define callback to format results
		source: function(req, add){
		
			// var txt = JSON.stringify(req);
			// alert(txt);
			
			// pack = '<pack><request city="'+ req.term +'"/></pack>';
			
			var pack = new RequestFactory();
			pack.CreateRequest("city", "sel", page_type, "city-list")
				.CreateSection("cond", "name", req.term);
			
			//pass request to server
			var res = $.ajax({
	            url: root_url+ "/aj.php",
				async: true,
				type: "POST",
				data: { xml: pack.toString() },
				dataType: "xml",
				success: function(xml, status, obj) {
					var data = $( "city", xml ).map(function() {
						return {
							value: this.getAttribute("name"), 
							region:	this.getAttribute("region"),
							population: this.getAttribute("population"),
							id: this.getAttribute("id")
						};
					}).get();
					add(data);
				}
			});
		},
		select: function(e, ui) {
			$("#h_city_id").val(ui.item.id);
				// "Selected: " + ui.item.value + ", ID: " + ui.item.id :
				// "Nothing selected, input was " + this.value );
		}
		
	})
	.data( "autocomplete" )._renderItem = function( ul, item ) {
		var popul = item.population == '0' ? '-' : item.population + " 000 чел."
		return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append(
				"<a>" + item.value +
				"<br/>" + item.region +
				"["+ popul +"]"  + "</a>" )
			.appendTo( ul );
	}

})


function prepare_before_show()
{
	// alert(var_dump(profile_form));
	
	// Установка даты рождения
	var rus_date = date_uni2rus($("#h_born").val());
	if($("#fld_born").val(rus_date));
	
	// Установка пола
	if($("#h_male").val() == "Y")
	{
		$("#radio_male_y").attr("checked", "checked");
		$("#radio_male_n").removeAttr("checked");
	}
	else
	{
		$("#radio_male_n").attr("checked", "checked");
		$("#radio_male_y").removeAttr("checked");
	}
}

function prepare_before_send()
{
	if($("#fld_username").val().length < 4)
	{
		$("#errorBox").text("Имя должно быть длинее 3-х символов");
		return false;
	}
	
	var uni_date = date_rus2uni($("#fld_born").val());
	$("#h_born").val(uni_date);
	
	var maleY = ($("#radio_male_y").attr("checked") == true) ? "Y" : "N";
	$("#h_male").val(maleY);
	
	return true;
}
